package com.molichuxing.services.util;

import com.molichuxing.services.infrastructure.dto.response.EsignCompanyDto;
import com.molichuxing.services.infrastructure.service.EsignCompanyService;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.ehcache.EhCacheCacheManager;

import java.util.List;

public class CompanySealDataCacheUtil {


	//private static Integer PartyC_id = 2;
	@Value("${party.c.id}")
	private String PARTY_C_ID;

	@Autowired
	EsignCompanyService esignCompanyService;

	private EhCacheCacheManager ehCacheCacheManager;

	public EhCacheCacheManager getEhCacheCacheManager() {
		return ehCacheCacheManager;
	}

	public void setEhCacheCacheManager(EhCacheCacheManager ehCacheCacheManager) {
		this.ehCacheCacheManager = ehCacheCacheManager;
	}



	private Cache getCompanySealDataCache() {
		return ehCacheCacheManager.getCacheManager().getCache("CompanySealDataCache");
	}

	private synchronized void getMoliSealData() {
		List<EsignCompanyDto> list = esignCompanyService.getEsignCompanyList();
		for (EsignCompanyDto esignCompanyDto : list) {
			if (esignCompanyDto.getCompanyId().toString().equals(PARTY_C_ID)) {
				Element ele = new Element("partyCSealData", esignCompanyDto.getSealData()); // 丙方章
				Cache companySealDataCache = getCompanySealDataCache();
				companySealDataCache.put(ele);
				ele = new Element("partyCName", esignCompanyDto.getFullName()); // 丙方公司名称
				companySealDataCache = getCompanySealDataCache();
				companySealDataCache.put(ele);
			} else {
				Element ele = new Element("partyASealData", esignCompanyDto.getSealData()); // 甲方章
				Cache companySealDataCache = getCompanySealDataCache();
				companySealDataCache.put(ele);
			}
		}
	}

	/**
	 * 甲方合同章
	 * 
	 * @return
	 */
	public String getPartyASealData() {
		Element partyASealData = getCompanySealDataCache().get("partyASealData");
		if (partyASealData == null) {
			getMoliSealData();
			partyASealData = getCompanySealDataCache().get("partyASealData");
		}

		return partyASealData.getObjectValue().toString();
	}

	/**
	 * 丙方合同章
	 * 
	 * @return
	 */
	public String getPartyCSealData() {
		Element partyCSealData = getCompanySealDataCache().get("partyCSealData");
		if (partyCSealData == null) {
			getMoliSealData();
			partyCSealData = getCompanySealDataCache().get("partyCSealData");
		}

		return partyCSealData.getObjectValue().toString();
	}

	/**
	 * 丙方公司名
	 * 
	 * @return
	 */
	public String getPartyCName() {
		Element partyCSealData = getCompanySealDataCache().get("partyCName");
		if (partyCSealData == null) {
			getMoliSealData();
			partyCSealData = getCompanySealDataCache().get("partyCName");
		}

		return partyCSealData.getObjectValue().toString();
	}

}
